<template>
  <q-layout view="lHr LpR fFf">
    <q-header class="bg-grey-3 text-black">
      <q-toolbar class="shadow-10 rounded-borders">
        <q-btn
          flat
          dense
          round
          icon="menu"
          aria-label="Menu"
          @click="toggleLeftDrawer"
        />

        <q-toolbar-title class="text-weight-bold text-grey-9">
          <q-avatar class="bg-white">
            <img :src="siteInfo.titleLogo">
          </q-avatar>
          {{ siteInfo.appName }} <span style="font-size: 0.9rem" v-if="userInfo.tenant">{{ userInfo.tenant.tenant_name }}</span>
        </q-toolbar-title>
        <q-space v-if="!$q.screen.xs" />
        <q-btn
          v-if="$q.fullscreen.isCapable"
          ref="fullscreen"
          flat
          dense
          round
          color="secondary"
          @click="$q.fullscreen.toggle()"
          :icon="$q.fullscreen.isActive ? 'fullscreen_exit' : 'fullscreen'"
        />
        <q-btn
          flat
          dense
          round
          icon="view_list"
          @click="toggleRightDrawer"
        >
          <q-badge color="red" floating v-if="newMessageCount > 0">{{newMessageCount}}</q-badge>
        </q-btn>
      </q-toolbar>
    </q-header>

    <q-drawer
      v-model="leftDrawerOpen"
      show-if-above
      bordered
      :width="260"
      :breakpoint="1279"
      content-class="bg-grey-1 shadow-18"
    >
      <q-scroll-area class="fit darkSideBar">
        <q-list class="listStyle">
          <menu-item
            v-for="item in mainMenu"
            :key="item.name"
            :menuitem="item"
          />
        </q-list>
      </q-scroll-area>
    </q-drawer>

    <q-drawer
      v-model="rightDrawerOpen"
      side="right"
      show-if-above
      bordered
      behavior="mobile"
    >
      <q-infinite-scroll
        style="height: calc(100% - 150px); margin-top: 150px; border-right: 1px solid #ddd"
        ref="messageScroll"
        :offset="300"
        :debounce="1000"
        @load="onMessageLoad"
        v-if="messages.length > 0"
      >
        <q-list padding>
          <message-item v-for="(msg, idx) in messages" :message="msg" :key="idx" />
        </q-list>
      </q-infinite-scroll>

      <q-img class="absolute-top" src="/images/material.png" style="height: 150px">
        <div class="absolute-bottom bg-transparent">
          <div class="flex items-end q-mb-sm">
            <q-avatar size="56px" class="shadow-2">
              <img :src="userInfo.user && userInfo.user.headimg || defaultHeadImg">
            </q-avatar>
            <q-btn
              v-if="IMType === 'wechat'"
              class="q-ml-sm"
              :color="userInfo.is_wechat ? 'grey' : 'secondary'"
              :label="userInfo.is_wechat ? '微信解绑' : '微信绑定'"
              dense size="sm"
              @click="bindWechat"
            />
          </div>
          <div class="text-weight-bold">{{ userInfo.user && userInfo.user.nickname }}，您好！</div>
          <div class="flex">
            <q-btn color="primary" dense label="修改密码" size="sm" @click="alert=true" />

            <q-space />
            <q-btn color="info" icon="exit_to_app" dense label="注销登录" size="sm" @click="exit" />
          </div>
        </div>
      </q-img>
    </q-drawer>

    <q-page-container>
      <router-view v-slot="{ Component }">
        <transition name="fade" mode="out-in" appear>
          <component :is="Component" ref="component" />
        </transition>
      </router-view>
    </q-page-container>

    <copyright isDark :tip="copyrightTip" @trigger="bindIM" />

    <q-dialog v-model="alert" @show="password = password2 = ''">
      <q-card style="width: 300px">
        <q-form ref="passwordForm">
          <q-card-section>
            <div class="text-h6">修改密码</div>
          </q-card-section>

          <q-card-section class="q-pt-none q-gutter-md">
            <q-input
              v-model="password"
              filled
              type="password"
              label="密码"
              :rules="[checkPassword]"
            />
            <q-input
              v-model="password2"
              filled
              type="password"
              label="再次输入"
              :rules="[val => val === password || '两次密码输入不同']"
            />
          </q-card-section>

          <q-card-actions align="right">
            <q-btn flat label="取消" color="primary" v-close-popup />
            <q-btn label="确定" color="primary" @click="changePassword"/>
          </q-card-actions>
        </q-form>
      </q-card>
    </q-dialog>

    <q-dialog v-model="confirmConfig.show" persistent>
      <q-card style="min-width: 600px; max-width: 80vw;">
        <q-card-section class="flex">
          <div class="text-h6">{{confirmConfig.title}}</div>
          <q-space />
          <q-btn dense flat icon="close" v-close-popup>
            <q-tooltip>关闭</q-tooltip>
          </q-btn>
        </q-card-section>

        <q-card-section class="q-pt-none" v-html="confirmConfig.content">
        </q-card-section>

        <q-card-actions align="right">
          <q-btn flat label="取消" color="primary" v-close-popup @click="confirmBoxClk(false)" v-if="confirmConfig.cancelBtn" />
          <q-btn label="确定" color="primary" v-close-popup @click="confirmBoxClk(true)" />
        </q-card-actions>
      </q-card>
    </q-dialog>

    <q-dialog v-model="promptConfig.show" persistent>
      <q-card style="min-width: 300px">
        <q-card-section>
          <div class="text-h6">{{promptConfig.title}}</div>
        </q-card-section>

        <q-card-section class="q-pt-none">
          <q-input ref="prompInput" dense :placeholder="'请输入'+promptConfig.title" v-model="promptConfig.value" :rules="promptConfig.rules" :suffix="promptConfig.suffix" autofocus @keyup.enter="confirmInput" />
        </q-card-section>

        <q-card-actions align="right" class="text-primary">
          <q-btn flat label="取消" v-close-popup />
          <q-btn label="确定" color="primary" @click="confirmInput" />
        </q-card-actions>
      </q-card>
    </q-dialog>

    <q-dialog v-model="noticeConfig.show" persistent>
      <q-card style="min-width: 300px">
        <q-card-section>
          <div class="text-h6">{{noticeConfig.title}}</div>
        </q-card-section>

        <q-card-section class="q-pt-none q-gutter-lg">
          <q-select
            filled
            emit-value
            map-options
            v-model="noticeConfig.value"
            :options="noticeConfig.options"
            :label="noticeConfig.label"
          />
        </q-card-section>

        <q-card-actions align="right" class="text-primary">
          <q-btn flat label="取消" v-close-popup />
          <q-btn label="确定" color="primary" @click="confirmNotice" />
        </q-card-actions>
      </q-card>
    </q-dialog>

    <dialogForm ref="approveDialog" :config="approveConfig" :buttonLabel="['确定', '取消']" />
  </q-layout>
</template>

<script>
import { defineComponent, ref } from 'vue';
import { useMeta, LocalStorage } from 'quasar';
import { mapState, mapActions } from 'pinia';
import { useStore } from 'stores/store';
import MenuItem from 'components/MenuItem.vue';
import dialogForm from 'components/DialogInputForm.vue';
import io from 'socket.io-client';
import copyright from 'components/copyright.vue';
import messageItem from 'components/MessageItem.vue';
import { browserInfo, osInfo } from '../lib/ClientInformation';
import md5 from 'md5';
import mitt from 'mitt';
const emitter = mitt();
import EventBus from 'src/lib/event-bus'; // 用于组件间通信

export default defineComponent({
  name: 'MainLayout',
  components: {
    MenuItem,
    copyright,
    messageItem,
    dialogForm
  },
  setup () {
    const $store = useStore();
    useMeta({
      // 设置文件标题
      title: `${$store.siteConfig.appName} - 木多鱼系列`,
      meta: {
        description: {
          name: 'description',
          content: $store.siteConfig.description || $store.siteConfig.subTitle
        }
      }
    });

    const leftDrawerOpen = ref(false);
    const rightDrawerOpen = ref(false);

    return {
      leftDrawerOpen,
      rightDrawerOpen,
      toggleLeftDrawer () {
        leftDrawerOpen.value = !leftDrawerOpen.value;
      },
      toggleRightDrawer () {
        rightDrawerOpen.value = !rightDrawerOpen.value;
      }
    }
  },
  data () {
    return {
      mainMenu: [],

      alert: false, // 密码修改弹窗口
      password: '',
      password2: '',

      // 确认提示窗口
      confirmConfig: {
        show: false,
        title: '',
        content: '',
        confirm: false,
        cancelBtn: true
      },

      // 输入窗口
      promptConfig: {
        show: false,
        title: '',
        value: '',
        confirm: false,
        rules: [],
        suffix: ''
      },

      // 通知窗口
      noticeConfig: {
        show: false,
        title: '',
        label: '',
        value: '',
        options: [],
        confirm: false
      },

      // 消息相关
      messages: [],
      newMessageCount: 0,
      messageTimer: null,

      browser: {
        name: '',
        ver: ''
      },
      userInfo: { user: {}, role: {}, tenant: {} },
      socket: null,
      caption: '',
      audio: null,

      approveConfig: { // 审批对话框配置
        title: '审批操作',
        fields: {
          state: {
            type: 'select',
            label: '审批类型',
            options: [],
            value: ''
          },
          opinion: {
            type: 'input',
            label: '审批意见',
            textarea: true,
            value: '',
            readonly: false
          }
        }
      }
    }
  },
  provide () { // 向其所有子孙后代注入一个依赖
    return {
      confirmBox: this.confirmBox,
      inputBox: this.inputBox,
      noticeUser: this.noticeUser,
      sendCooperation: this.sendCooperation,
      approveBox: this.approveBox
    }
  },
  beforeRouteEnter (to, from, next) { // 前置路由守卫
    // 检测权限
    let { rights } = LocalStorage.getItem('user');

    if (rights && typeof rights === 'string') {
      rights = JSON.parse(rights);
    }

    const subPath = to.path.split('/')[2];
    const unRight = ['config']; // 不检查权限的子路径

    if (rights && !unRight.includes(subPath)) {
      if (rights && rights[subPath] && rights[subPath].func) {
        next(vm => {
          vm.changeCaptionByPath(to.path); // 根据路径设置标题
        });
      } else {
        if (subPath == 'index') {
          next(vm => {
            vm.goSubIndexPage(); // 首页没权限，从上往下找最近一个有权限的菜单
          });
        } else {
          next('/404');
        }
      }
    } else {
      next(vm => {
        vm.changeCaptionByPath(to.path); // 根据路径设置标题
      });
    }
  },
  // 当前路由改变，并且该组件被复用时调用的路由守卫
  beforeRouteUpdate (to, from, next) {
    this.changeCaptionByPath(to.path); // 根据路径设置标题
    next();
  },
  async created () {
    // 登录后重新加载以触发preFetch
    // if (Object.keys(this.menuInfo).length === 0) {
    //   location.reload();
    // }
    // 若无地区数据则从服务器获取，并存入idb
    const region = await this.$idb.get('config', 'region');
    if (!region) {
      this.$axios.get('/c/system/getRegions').then(({ data }) => {
        this.$idb.put('config', data, 'region');
      });
    }
  },
  async mounted () {
    this.browser = {
      name: browserInfo().browser,
      ver: browserInfo().ver
    }
    await this.refreshUserInfo();

    if (!this.userInfo.tenant) return;

    // 初始化socket
    this.initSocket({
      id: this.userInfo.user.id,
      nickname: this.userInfo.user.nickname,
      tid: this.userInfo.tenant.id,
      browser: `${this.browser.name} ${this.browser.ver}`,
      os: osInfo()
    });

    // 请求消息通知
    Notification.requestPermission()
      .then(() => console.log('Notification permission granted'))
      .catch(e => console.log('Unable to get permission to notify.', e));

    // 读取新消息数量
    this.refreshNewMessageCount();

    // 初始化人员信息
    this.$axios.post('/c/system/getDataDict', { types: ['user'] }).then(({ data }) => {
      this.initDictionary(data);
    });
  },
  methods: {
    ...mapActions(useStore, ['initDictionary', 'setUserMenu', 'setMenuInfo']),
    exit () {
      const url = this.userInfo.tenant.id > 0 ? '/tLogin' : '/mLogin';
      const tenant = this.$q.localStorage.getItem('tenant_login');
      this.$q.localStorage.clear();
      this.$q.localStorage.set('tenant_login', tenant);
      window.location.replace(url);
    },
    // 刷新登录用户信息
    async refreshUserInfo () {
      // const { state, code } = this.$route.query;
      // if (state && code && !this.userInfo.is_wechat && this.browser.name === 'micromessenger') {
      //   // 绑定微信
      //   await this.$axios.post('/c/wechat/bind', { code, state });
      // }

      const { user, role, tenant } = (await this.$axios.get('/c/system/getUserInfo')).data;
      this.userInfo = { user, role, tenant };

      // 被禁用，退出登录
      if (!user.state || !tenant.state) {
        this.exit();
        return false;
      }

      this.$q.localStorage.set('user', user);
      this.$q.localStorage.set('role', role);
      this.$q.localStorage.set('tenant', tenant);

      if (!user.headimg) {
        this.userInfo.user.headimg = this.defaultHeadImg;
      }

      this.filterMainMenu();
    },
    async filterMainMenu () { // 根据权限过滤菜单
      const type = this.userInfo.tenant.id > 0 ? 't' : 'm';
      const { menu, dictionary } = (await this.$axios.get('/c/system/getGeneralConfig', { params: { type } })).data;

      this.setMenuInfo(menu);
      this.initDictionary(dictionary);
      this.mainMenu = JSON.parse(JSON.stringify(this.menuInfo.tree));

      const self = this;
      // 给菜单设置权限
      function dfsRight (node) {
        if (node.type === 'menu') {
          let func = false;
          if (self.userInfo.user.rights[node.name] && self.userInfo.user.rights[node.name].func) func = true;
          node.func = func;
        } else if (node.children && node.children.length > 0) {
          node.children.forEach(child => dfsRight(child));
        }
      }
      this.mainMenu.forEach(node => dfsRight(node));

      // 把没有子项的分类菜单设置不显示
      function dfsChild (node) {
        if (node.type === 'label') {
          node.func = node.children && node.children.filter(v => v.func).length > 0;
          node.children && node.children.forEach(child => dfsChild(child));
        }
      }
      this.mainMenu.forEach(node => dfsChild(node));
    },
    async initSocket (user) {
      this.socket = io();

      this.socket.on('connect', () => {
        this.socket.emit('login', user); // 发送登录
      });

      // 收到指令
      this.socket.on('command', cmd => {
        if (cmd.command.message) {
          this.$q.notify({
            message: `${cmd.from.nickname}：${cmd.command.message}`,
            icon: 'announcement',
            color: 'primary',
            html: true,
            progress: true,
            actions: [
              { label: '关闭', color: 'yellow', handler: () => { /* ... */ } }
            ]
          });
          let url = cmd.command.module;
          if (url.indexOf('main/') < 0) {
            if (url.split('/')[0]) {
              url = `/main/${url}`;
            } else {
              url = `/main${url}`;
            }
          }
          this.showNotification(cmd.from.nickname, cmd.command.message, url);
          console.log('command', cmd);

          this.refreshNewMessageCount();
        }
      });

      this.socket.on('message', msg => {
        this.refreshNewMessageCount();
        console.log('message', msg);
      })
      this.socket.on('online', data => {
        // this.showNotification('上线通知', `${data.user.nickname}上线 共${data.users}人${data.connects}连接在线`);
        console.log('上线通知', `${data.user.nickname}上线 共${data.users}人${data.connects}连接在线`);
      })
      this.socket.on('offline', data => {
        // this.showNotification('下线通知', `${data.user.nickname}下线 共${data.users}人${data.connects}连接在线`);
        console.log('下线通知', `${data.user.nickname}下线 共${data.users}人${data.connects}连接在线`);
      })

      this.socket.on('cooperation', async (data) => {
        /*
        消息结构
        from: {
          id: 发送人id,
          nickname: 发送人昵称
        },
        message: {
          type: 类型
          data: 数据，自定义，不固定
        }
        */
        // console.log('cooperation', data);
        const { message } = data;
        switch (message.type) {
          case 'refresh_dict': // 刷新数据字典
            this.initDictionary((await this.$axios.post('/c/system/getDataDict', {
              types: message.data
            })).data);
            break;
          case 'refresh_user': // 刷新权限
            this.refreshUserInfo();
            break;
        }
      });
      this.socket.on('broadcast', async (data) => {
        console.log('broadcast', data);
        EventBus.emit(data.type, data.message);
      });
    },
    // 发送消息 to 接收人的id或nickname，均可, message - 消息体
    /**
     * 通过socket给其它用户发送协同消息
     * @param {object, string} message 消息体
     * @param {string, array} to 接收人 * - 广播所有人，可发送用户id或是昵称，多人用数组
     */
    sendCooperation (message, to) {
      if (this.socket) {
        this.socket.emit('cooperation', {
          to: to || '*',
          message
        });
      }
    },
    showNotification (title, message, routeTo) { // 显示pop消息 windows chrome有效
      const self = this;
      Notification.requestPermission().then(status => {
        if (status === 'granted') {
          const notify = new Notification(title, {
            icon: 'public/icons/favicon-128x128.png',
            body: message
          })

          // 桌面消息显示时
          notify.onshow = () => {
            // const audio = new Audio('./mp3/test2.mp3');
            // audio.play();
          }
          // 点击时桌面消息时触发
          notify.onclick = () => {
            // 跳转到当前通知的tab,如果浏览器最小化，会将浏览器显示出来
            window.focus();
            if (routeTo) {
              // this.$router.push(routeTo);
              window.location.href = `${window.location.origin}${routeTo}`;
            }
          }
        }
      });
    },
    checkPassword (val) {
      return new Promise((resolve, reject) => {
        const reg = /^(?![\d]+$)(?![a-zA-Z]+$)(?![^\da-zA-Z]+$).{6,20}$/;
        if (val && val.length > 0) resolve(reg.test(val) || '需要6~10位的 数字+字母 或 字母+特殊字符 或 特殊字符+数字');
        else resolve(true);
      });
    },
    changePassword () {
      const self = this;
      this.$refs.passwordForm.validate().then(res => {
        if (res) {
          self.alert = false;
          self.$axios.post('/c/system/changePwd', { pwd: md5(self.password) }).then(({ data }) => {
            if (data.result === 'fail') {
              self.$q.notify({
                message: data.message || '密码修改失败',
                color: 'negative',
                icon: 'error',
                position: 'top',
                timeout: 2000
              });
            } else {
              self.$q.notify({
                message: '密码修改成功',
                color: 'secondary',
                icon: 'done',
                position: 'top',
                timeout: 2000
              });
            }
          });
        }
      });
    },
    confirmBox (title, content, cancelBtn = true) {
      const self = this;
      return new Promise((resolve, reject) => {
        self.confirmConfig.confirm = false;
        self.confirmConfig.title = title;
        self.confirmConfig.content = content;
        self.confirmConfig.show = true;
        self.confirmConfig.cancelBtn = cancelBtn;

        emitter.on('confirmBox', ot => {
          resolve(ot);
        });
      });
    },
    confirmBoxClk (result) {
      this.confirmConfig.confirm = result;
      emitter.emit('confirmBox', result);
    },
    inputBox (title, value, config) {
      const self = this;
      return new Promise((resolve, reject) => {
        self.promptConfig.confirm = false;
        self.promptConfig.title = title;
        self.promptConfig.value = value;
        self.promptConfig.show = true;
        if (config) {
          const { rules, suffix } = config;
          self.promptConfig.rules = rules || [];
          self.promptConfig.suffix = suffix || '';
        }
        self.$nextTick(() => { self.$refs.prompInput.select(); });

        emitter.on('confirmInput', ot => {
          if (ot) {
            resolve(self.promptConfig.value);
          } else {
            resolve('');
          }
        });
      });
    },
    confirmInput () {
      if (this.promptConfig.rules.length > 0) {
        const outcome = this.$refs.prompInput.validate();
        this.promptConfig.confirm = outcome;
        this.promptConfig.show = !outcome;
      } else {
        this.promptConfig.confirm = true;
        this.promptConfig.show = false;
      }
      emitter.emit('confirmInput', this.promptConfig.confirm);
    },
    noticeUser (title, label, value, rights = 'all') { // right: all - 所有 [{module, func, right},...]
      const self = this;
      return new Promise((resolve, reject) => {
        self.noticeConfig.title = title;
        self.noticeConfig.label = label;
        self.noticeConfig.show = true;

        if (rights == 'all') {
          self.noticeConfig.options = self.dictionary.user.map(v => { return { value: v.value, label: v.label } });
        } else {
          self.noticeConfig.options = self.dictionary.user.filter(v => {
          // 匹配有权限的用户
            const userRights = JSON.parse(v.rights);
            let flag = true;
            for (const item of rights) {
              if (!userRights[item.module] || userRights[item.module][item.func] != item.right) {
                flag = false;
                break;
              }
            }
            return flag;
          }).map(v => { return { value: v.value, label: v.label } });

          if (self.noticeConfig.options.length > 0) {
            self.noticeConfig.value = value || self.noticeConfig.options[0].value;
          }
        };

        const timer = setInterval(() => {
          if (!self.noticeConfig.show) {
            clearInterval(timer);
            if (self.noticeConfig.confirm) {
              resolve(self.noticeConfig.value);
            } else {
              resolve('');
            }
          }
        }, 50);
      });
    },
    confirmNotice () {
      this.noticeConfig.confirm = true;
      this.noticeConfig.show = false;
    },
    refreshNewMessageCount () {
      this.$axios.get('/c/system/getNewMessageCount').then(res => {
        this.newMessageCount = res.data.newMessage;
      });
    },
    queryMessage (index, cb) {
      const self = this;
      this.$axios.post('/c/system/getUserMessage', { page: index }).then(res => {
        if (res.data.length === 0) { // 没数据的，暂停取
          self.$refs.messageScroll && self.$refs.messageScroll.stop();
        }
        if (index == 1 && self.messages.length > 0) { // 取第一页数据时，对已有数据清空
          self.messages = [];
        }
        self.messages = [...self.messages, ...res.data];
        cb && cb();

        if (this.messageTimer) {
          clearTimeout(this.messageTimer);
          this.messageTimer = null;
          this.refreshNewMessageCount();
        }
        this.messageTimer = setTimeout(() => {
          self.messages.forEach(item => {
            item.is_new = 0;
          });
          self.messageTimer = null;
          self.refreshNewMessageCount();
        }, 10000);
      });
    },
    onMessageLoad (index, done) {
      this.queryMessage(index, () => {
        done();
      });
    },
    bindWechat () { // 绑定或解绑微信
      if (!this.userInfo.is_wechat) { // 获取微信授权链接并跳转
        if (this.browser.name === 'micromessenger') {
          this.$axios.get('/c/wechat/getAuthorizeURL').then(res => {
            if (res.data) {
              window.location.href = res.data;
            }
          });
        } else {
          this.$q.notify({
            message: '先微信关注公司公众号，再从公众号菜单登录系统后绑定。', color: 'negative', icon: 'error', position: 'top', timeout: 2000
          });
        }
      } else { // 解绑
        this.$axios.get('/c/wechat/unbind').then(res => {
          this.refreshUserInfo();
        });
      }
    },
    bindDingtalk () { // 绑定或解绑钉钉
    },
    bindIM () {
      if (this.IMType == 'wechat') {
        this.bindWechat();
      } else if (this.IMType == 'dingtalk') {
        this.bindDingtalk();
      }
    },
    approveBox (currentState, opinion, title) {
      if (title) this.approveConfig.title = title;

      if (currentState == 'pass') { // 通过
        this.approveConfig.fields.state.options = [{ value: 'none', label: '撤销审批' }];
        this.approveConfig.fields.state.value = 'none';
        this.approveConfig.fields.opinion.readonly = true;
      } else {
        this.approveConfig.fields.state.options = this.dictionary.approvalState.filter(v => v.value != 'none');
        this.approveConfig.fields.state.value = 'pass';
        this.approveConfig.fields.opinion.readonly = false;
      }

      this.approveConfig.fields.opinion.value = opinion || '';

      return this.$refs.approveDialog.show();
    },
    changeCaptionByPath (path) { // 修改网站标题
      const pathArr = path.split('/');
      this.caption = '';

      if (!this.menuInfo.menu) return;

      if (pathArr.length === 3) {
        const ret = this.menuInfo.menu.filter(v => v.type === 'menu' && v.name === pathArr[2]);
        if (ret.length > 0) {
          this.caption = ret[0].caption + ' ';
        }
      }
    },
    async goSubIndexPage () { // 首页没权限，从上往下找最近一个有权限的菜单
      await this.refreshUserInfo();
      let path = '/404'

      for (const item of this.menuInfo.menu) {
        if (item.type === 'menu' && this.userInfo.user.rights[item.name].func) {
          path = `/main/${item.name}`
          break;
        }
      }

      this.$router.push({ path });
    },
    getMainMenu () {
      return this.mainMenu;
    }
  },
  computed: {
    ...mapState(useStore, ['siteInfo', 'dictionary', 'defaultHeadImg', 'menuInfo', 'rights']),
    IMType () {
      if (this.siteInfo.can_wechat && this.browser.name === 'micromessenger') {
        return 'wechat';
      } else {
        return '';
      }
    },
    copyrightTip () {
      if (this.IMType == 'wechat' && !this.userInfo.is_wechat) {
        return 'wechat';
      } else if (this.IMType == 'dingtalk' && !this.userInfo.is_dd) {
        return 'dingtalk';
      } else {
        return '';
      }
    }
  },
  watch: {
    rightDrawerOpen (val) {
      if (!val) { // 消息栏展开时，10秒后，刷新新消息数据，把当前新消息置为已读
        if (this.messageTimer) {
          clearTimeout(this.messageTimer);
          this.messageTimer = null;
        }
        this.refreshNewMessageCount();
      } else {
        this.queryMessage(1);
      }
    }
  }
})
</script>

<style lang="scss">
.darkSideBar {
  background-image: linear-gradient(rgba(0, 0, 0, 0.8), rgba(0, 0, 0, 0.8)), url("/images/sidebar-1.jpg");
  background-position: center center;
  background-size: 100% 100%;
}
.listStyle {
  padding: 10px;
}

.q-item.q-router-link--active, .q-item--active {
    color: #e8e8e8;
    background-color: $blue-6!important;// #4CAF50 !important;
    border-radius: 4px;
}
</style>
